package com.xiaocg.base.thread.pool;

class Test{
    private int count=0;
    public synchronized void increment(){
        System.out.println("------------锁对象是this --- 当前调用方法的对象");
        count++;
    }
    public synchronized void decrement(){
        System.out.println("------------锁对象是this --- 当前调用方法的对象");
        count--;
    }
    public synchronized int getCount(){
        System.out.println("------------锁对象是this --- 当前调用方法的对象");
        return count;
    }

    public static synchronized void print(){
        System.out.println("------------锁对象是Test.class ----类对象");
    }

}
/**
 * @author xiaocg
 */
public class ThreadJoinTest {
    static int count=0;
    static Object object= new Object();
    public static void main(String[] args) throws Exception{
        //extracted();
        extracted1();
    }

    /**
     * 通过在同一个对象上加锁互斥，实现线程安全
     * @throws InterruptedException
     */
    private static void extracted1() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                synchronized (object) {
                    count++;
                }
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                synchronized (object) {
                    count--;
                }
            }
        });

        t1.start();
        t2.start();
        System.out.println("main join");
        long start = System.currentTimeMillis();
        t1.join();
        t2.join();
        System.out.println("main over time:"+(System.currentTimeMillis()-start));
        System.out.println("count2:"+count);
        String s = "::";
        s.substring(1);
    }

    /**
     * 多个线程对同一资源读写的时候，存在线程上下文切换，产生线程安全问题
     * @throws InterruptedException
     */
    private static void extracted() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                count++;
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                count--;
            }
        });

        t1.start();
        t2.start();
        System.out.println("main join");
        long start = System.currentTimeMillis();
        t1.join();
        t2.join();
        System.out.println("main over time:"+(System.currentTimeMillis()-start));
        System.out.println("count:"+count);
    }
}
